package com.wedo.book.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wedo.book.mapper.BookHotMapper;
import com.wedo.book.mapper.BookMapper;
import com.wedo.book.mapper.ChapterMapper;
import com.wedo.book.pojo.Book;
import com.wedo.book.pojo.BookHot;
import com.wedo.book.pojo.Chapter;
import com.wedo.book.result.BookHotResult;
import com.wedo.common.pojo.PageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
@CacheConfig(cacheNames = "book")
public class BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private BookHotMapper bookHotMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Cacheable(key = "'queryBookByPage.'+#title+'.'+#page+'.'+#rows")
    public PageResult<Book> queryBookByPage(String title, Long cid, Integer page, Integer rows) {
        Example example = new Example(Book.class);
        Example.Criteria criteria = example.createCriteria();

        // 添加查询条件
        if (StringUtils.isNotBlank(title)) {
            criteria.andLike("title", "%" + title + "%");
        }

        if (cid != null) {
            criteria.andEqualTo("cId",cid);
        }

        // 添加分页
        PageHelper.startPage(page, rows);
        List<Book> books = bookMapper.selectByExample(example);
        PageInfo<Book> pageInfo = new PageInfo<>(books);

        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), books);
    }

    /**
     * 根据分类id查询
     *
     * @param cid
     * @param page
     * @param rows
     * @return
     */
    @Cacheable(key = "'queryBookPageByCid.'+#cid+'.'+#page+'.'+#rows")
    public PageResult<Book> queryBookPageByCid(Long cid, Integer page, Integer rows) {
        Example example = new Example(Book.class);
        Example.Criteria criteria = example.createCriteria();

        // c_id == cid
        criteria.andEqualTo("cId", cid);

        // 添加分页
        PageHelper.startPage(page, rows);

        // 查询
        List<Book> books = this.bookMapper.selectByExample(example);
        PageInfo<Book> pageInfo = new PageInfo<>(books);


        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), books);

    }

    @Cacheable(key = "'queryBookPageByAid.'+#aid+'.'+#page+'.'+#rows")
    public PageResult<Book> queryBookPageByAid(Long aid, Integer page, Integer rows) {
        Example example = new Example(Book.class);
        Example.Criteria criteria = example.createCriteria();

        // 添加分页
        PageHelper.startPage(page, rows);
        // c_id == cid
        criteria.andEqualTo("aId", aid);
        List<Book> books = this.bookMapper.selectByExample(example);
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), books);
    }

    @Cacheable(key = "'queryBookByBid.'+#bid")
    public Book queryBookByBid(Long bid) {
        return this.bookMapper.selectByPrimaryKey(bid);
    }

    @CacheEvict(value = "book", allEntries=true)
    public void updateBookById(Book book) {
        book.setUpdateDate(new Date());
        this.bookMapper.updateByPrimaryKeySelective(book);
        this.sendMsg("update",book.getId());
    }

    @Transactional
    @CacheEvict(value = "book", allEntries=true)
    public void saveBook(Book book) {
        book.setId(null);
        book.setCreatDate(new Date());
        book.setUpdateDate(new Date());
        // 保存图书信息
        this.bookMapper.insertSelective(book);
        // 初始化book_hot
        BookHot bookHot = new BookHot();
        bookHot.setbId(book.getId());
        bookHot.setClickNum(0);
        bookHot.setHot(0);
        bookHot.setSearchNum(0);
        this.bookHotMapper.insert(bookHot);
        this.sendMsg("insert",book.getId());
    }

    @Transactional
    @CacheEvict(value = {"book","chapter"}, allEntries=true)
    public void deleteBook(Long id) {
        // 删除图书信息
        this.bookMapper.deleteByPrimaryKey(id);
        // 删除图书对应的章节
        Example example = new Example(Chapter.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("bId", id);
        this.chapterMapper.deleteByExample(example);

        // 删除图书对应的热度信息
        this.bookHotMapper.deleteByPrimaryKey(id);
        this.sendMsg("delete",id);
    }

    @Cacheable(key = "'queryBooksByCidAndHot.'+#cid+'.'+#rows")
    public List<BookHotResult> queryBooksByCidAndHot(Long cid, Integer rows) {
        return this.bookMapper.queryBooksByCidAndHot(cid, rows);
    }

    public void sendMsg(String type, Long id) {
        try {
            this.amqpTemplate.convertAndSend("book." + type, id);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }
}
